<template>
  <view class="dashboard-container">
    <view class="dashboard-header">
      <text class="dashboard-title">项目数据可视化看板</text>
    </view>
    
    <!-- 统计卡片区域 -->
    <view class="stats-grid">
      <view class="stat-card">
        <view class="stat-number" :class="{ 'loading': isLoading }">
          {{ isLoading ? '--' : totalProjects }}
        </view>
        <view class="stat-label">总项目数</view>
      </view>
      <view class="stat-card">
        <view class="stat-number" :class="{ 'loading': isLoading }">
          {{ isLoading ? '--' : completedProjects }}
        </view>
        <view class="stat-label">已完成项目</view>
      </view>
      <view class="stat-card">
        <view class="stat-number" :class="{ 'loading': isLoading }">
          {{ isLoading ? '--' : inProgressProjects }}
        </view>
        <view class="stat-label">进行中项目</view>
      </view>
      <view class="stat-card">
        <view class="stat-number" :class="{ 'loading': isLoading }">
          {{ isLoading ? '--' : totalAmount }}
        </view>
        <view class="stat-label">总金额(万元)</view>
      </view>
    </view>

    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-message">
      <text>{{ errorMessage }}</text>
      <button class="retry-btn" @click="loadDashboardData">重试</button>
    </view>

    <!-- 图表区域 -->
    <view class="charts-container">
      <view class="chart-section">
        <view class="chart-title">项目状态分布</view>
        <view class="chart-content" v-if="!isLoading">
          <view class="pie-chart" :style="{ background: `conic-gradient(#4CAF50 0deg ${completedAngle}deg, #FF9800 ${completedAngle}deg ${progressAngle}deg, #F44336 ${progressAngle}deg 360deg)` }">
          </view>
          <view class="chart-legend">
            <view class="legend-item">
              <view class="legend-color completed"></view>
              <text>已完成 ({{ completedProjects }})</text>
            </view>
            <view class="legend-item">
              <view class="legend-color progress"></view>
              <text>进行中 ({{ inProgressProjects }})</text>
            </view>
            <view class="legend-item">
              <view class="legend-color pending"></view>
              <text>待开始 ({{ pendingProjects }})</text>
            </view>
          </view>
        </view>
        <view v-else class="loading-placeholder">
          <text>加载中...</text>
        </view>
      </view>

      <view class="chart-section">
        <view class="chart-title">月度项目创建趋势</view>
        <view class="chart-content" v-if="!isLoading && monthlyData.length > 0">
          <view class="bar-chart">
            <view class="bar-item" v-for="(item, index) in monthlyData" :key="index">
              <view class="bar" :style="{ height: item.height + '%' }" :title="`${item.month}: ${item.value}个项目`">
                <text class="bar-value" v-if="item.value > 0">{{ item.value }}</text>
              </view>
              <text class="bar-label">{{ item.month }}</text>
            </view>
          </view>
        </view>
        <view v-else-if="isLoading" class="loading-placeholder">
          <text>加载中...</text>
        </view>
        <view v-else class="loading-placeholder">
          <text>暂无数据</text>
        </view>
      </view>
    </view>

    <!-- 快速操作区域 -->
    <view class="quick-actions">
      <view class="action-title">快速操作</view>
      <view class="action-buttons">
        <button class="action-btn primary" @click="refreshData">刷新数据</button>
        <button class="action-btn secondary" @click="showExportModal">导出报告</button>
      </view>
    </view>
    
    <!-- 导出报告模态框 -->
    <ExportReportModal 
      :visible="showExportModalFlag" 
      @close="closeExportModal"
      @export="handleExportReport"
    />
    
  </view>
</template>

<script>
import ExportReportModal from './ExportReportModal.vue'

export default {
  name: 'DashboardComponent',
  components: {
    ExportReportModal
  },
  data() {
    return {
      // 模态框控制
      showExportModalFlag: false,
      // 统计数据
      totalProjects: 0,
      completedProjects: 0,
      inProgressProjects: 0,
      totalAmount: 0,
      
      // 月度数据
      monthlyData: [],
      
      // 加载状态
      isLoading: false,
      
      // 错误信息
      errorMessage: ''
    }
  },
  computed: {
    pendingProjects() {
      return this.totalProjects - this.completedProjects - this.inProgressProjects;
    },
    completedAngle() {
      return this.totalProjects > 0 ? (this.completedProjects / this.totalProjects) * 360 : 0;
    },
    progressAngle() {
      return this.completedAngle + (this.totalProjects > 0 ? (this.inProgressProjects / this.totalProjects) * 360 : 0);
    },
    pendingAngle() {
      return this.progressAngle + (this.totalProjects > 0 ? (this.pendingProjects / this.totalProjects) * 360 : 0);
    }
  },
  mounted() {
    this.loadDashboardData();
  },
  methods: {
    // 获取token
    getToken() {
      return uni.getStorageSync('userInfo').token;
    },
    
    // 加载看板数据
    async loadDashboardData() {
      this.isLoading = true;
      this.errorMessage = '';
      
      try {
        const projects = await this.fetchProjectsData();
        this.generateMonthlyData(projects);
      } catch (error) {
        console.error('加载看板数据失败:', error);
        this.errorMessage = '数据加载失败，请稍后重试';
        this.showFallbackData();
      } finally {
        this.isLoading = false;
      }
    },
    
    // 获取项目数据并计算统计信息
    fetchProjectsData() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: './api/projects',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${this.getToken()}`
          },
          success: (res) => {
            if (res.statusCode === 200 && Array.isArray(res.data)) {
              const projects = res.data;
              
              // 计算统计数据
              this.totalProjects = projects.length;
              this.completedProjects = projects.filter(p => p.isacc === 'true').length;
              this.inProgressProjects = projects.filter(p => p.isacc === 'false').length;
              
              // 计算总金额（转换为万元）
              const totalCost = projects.reduce((sum, p) => sum + (parseFloat(p.cost) || 0), 0);
              this.totalAmount = Math.round(totalCost / 10000 * 100) / 100;
              
              resolve(projects);
            } else {
              reject(new Error('数据格式错误'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    
    // 基于实际项目创建时间生成月度数据
    generateMonthlyData(projects) {
      const currentDate = new Date();
      const currentMonth = currentDate.getMonth() + 1;
      const currentYear = currentDate.getFullYear();
      
      // 创建最近6个月的数据结构
      const monthlyStats = {};
      const months = [];
      
      for (let i = 5; i >= 0; i--) {
        let month = currentMonth - i;
        let year = currentYear;
        
        if (month <= 0) {
          month += 12;
          year -= 1;
        }
        
        const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
        monthlyStats[monthKey] = {
          month: `${month}月`,
          count: 0,
          year: year
        };
        months.push(monthKey);
      }
      
      // 统计每个月的项目创建数量
      if (projects && Array.isArray(projects)) {
        projects.forEach(project => {
          if (project.create_time) {
            try {
              const createDate = new Date(project.create_time);
              const projectMonth = createDate.getMonth() + 1;
              const projectYear = createDate.getFullYear();
              const projectKey = `${projectYear}-${projectMonth.toString().padStart(2, '0')}`;
              
              if (monthlyStats[projectKey]) {
                monthlyStats[projectKey].count++;
              }
            } catch (error) {
              console.warn('解析项目创建时间失败:', project.create_time, error);
            }
          }
        });
      }
      
      // 计算最大值用于高度计算
      const maxCount = Math.max(...Object.values(monthlyStats).map(item => item.count), 1);
      
      // 生成最终的月度数据
      this.monthlyData = months.map(monthKey => {
        const stat = monthlyStats[monthKey];
        return {
          month: stat.month,
          height: Math.max(10, (stat.count / maxCount) * 100), // 最小高度10%
          value: stat.count
        };
      });
    },
    
    // 显示备用数据
    showFallbackData() {
      this.totalProjects = 0;
      this.completedProjects = 0;
      this.inProgressProjects = 0;
      this.totalAmount = 0;
      this.monthlyData = [];
    },
    
    // 刷新数据
    async refreshData() {
      uni.showLoading({
        title: '刷新中...',
        mask: true
      });
      
      try {
        await this.loadDashboardData();
        uni.showToast({
          title: '数据已刷新',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 显示导出模态框
    showExportModal() {
      this.showExportModalFlag = true;
    },
    
    // 关闭导出模态框
    closeExportModal() {
      this.showExportModalFlag = false;
    },
    
    // 处理导出报告
    async handleExportReport(exportParams) {
      uni.showLoading({
        title: '正在导出报告...',
        mask: true
      });
      
      try {
        const token = this.getToken();
        if (!token) {
          throw new Error('未找到认证令牌，请重新登录');
        }
        
        // 发送导出请求
        const response = await this.requestExportReport(exportParams, token);
        
        if (response.statusCode === 200) {
          // 成功导出
          uni.showToast({
            title: '报告导出成功',
            icon: 'success'
          });
          
          // 如果是在浏览器环境，可以尝试下载文件
          if (typeof window !== 'undefined' && response.data) {
            this.downloadPdfFile(response.data);
          }
        } else {
          throw new Error(response.data?.error || '导出失败');
        }
        
      } catch (error) {
        console.error('导出报告失败:', error);
        
        let errorMessage = '导出报告失败';
        if (error.message) {
          errorMessage = error.message;
        }
        
        uni.showModal({
          title: '导出失败',
          content: errorMessage,
          showCancel: false
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 发送导出请求
    requestExportReport(requestData, token) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: './api/export_report',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          data: requestData,
          responseType: 'arraybuffer', // 用于接收PDF文件
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    
    // 下载PDF文件（仅在浏览器环境中有效）
    downloadPdfFile(arrayBuffer) {
      try {
        if (typeof window === 'undefined') {
          // console.log('非浏览器环境，无法直接下载文件');
          return;
        }
        
        // 创建Blob对象
        const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        
        // 生成文件名
        const now = new Date();
        const timestamp = now.getFullYear() + 
                         (now.getMonth() + 1).toString().padStart(2, '0') + 
                         now.getDate().toString().padStart(2, '0') + '_' +
                         now.getHours().toString().padStart(2, '0') + 
                         now.getMinutes().toString().padStart(2, '0') + 
                         now.getSeconds().toString().padStart(2, '0');
        
        link.download = `项目验收报告_${timestamp}.pdf`;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
      } catch (error) {
        console.error('下载文件失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.dashboard-header {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.dashboard-title {
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  text-align: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 12px;
}

.stat-card {
  background: white;
  padding: 12px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: #007aff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
  flex: 1;
  min-height: 0;
}

.chart-section {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  flex: 1;
  width: 100%;
  box-sizing: border-box;
}

.chart-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  text-align: center;
}

.chart-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
  width: 100%;
}

.pie-chart {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: conic-gradient(
    #4CAF50 0deg 120deg,
    #FF9800 120deg 240deg,
    #F44336 240deg 360deg
  );
  margin: 0 auto 12px;
  flex-shrink: 0;
}

.chart-legend {
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  width: 100%;
  margin-top: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-color {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.legend-color.completed {
  background-color: #4CAF50;
}

.legend-color.progress {
  background-color: #FF9800;
}

.legend-color.pending {
  background-color: #F44336;
}

.legend-item text {
  font-size: 10px;
  color: #666;
}

.bar-chart {
  display: flex;
  align-items: end;
  justify-content: space-around;
  height: 120px;
  padding: 12px 8px;
  flex: 1;
  width: 100%;
  box-sizing: border-box;
}

.bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.bar {
  width: 20px;
  background: linear-gradient(to top, #007aff, #5ac8fa);
  border-radius: 3px 3px 0 0;
  margin-bottom: 6px;
  position: relative;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.bar-value {
  font-size: 8px;
  color: white;
  font-weight: bold;
  padding-bottom: 1px;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.bar-label {
  font-size: 10px;
  color: #666;
}

.quick-actions {
  background: white;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  flex-shrink: 0;
}

.action-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 8px;
  border-radius: 6px;
  font-size: 12px;
  border: none;
  cursor: pointer;
}

.action-btn.primary {
  background-color: #007aff;
  color: white;
}

.action-btn.secondary {
  background-color: #f0f0f0;
  color: #333;
}

/* 加载状态样式 */
.stat-number.loading {
  color: #ccc;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* 错误提示样式 */
.error-message {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 8px;
  padding: 12px;
  margin: 12px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error-message text {
  color: #f56c6c;
  font-size: 12px;
}

.retry-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 10px;
  cursor: pointer;
}

/* 加载占位符样式 */
.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #999;
  font-size: 12px;
  flex: 1;
}
</style>